/**
 * 
 */
package com.wolfpire.system.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.wolfpire.system.common.base.dao.impl.BaseHibernateDao;
import com.wolfpire.system.dao.OrgUserRelationDao;
import com.wolfpire.system.model.OrgUserRelation;

/**
 * @author lihd
 *
 */

@Repository("orgUserRelationDao")
public class OrgUserRelationDaoImpl extends BaseHibernateDao<OrgUserRelation, Long> implements OrgUserRelationDao {

	@Override
	public void relate(Long userId, Long orgId) {
		//先删除后绑定
		this.deleteByUserId(userId);
		if (null != orgId) {
			OrgUserRelation ou = new OrgUserRelation(userId, orgId);
			this.saveOrUpdate(ou);
		}
	}

	private void deleteByUserId(Long userId) {
		String executeSql = "DELETE FROM t_sm_user_org WHERE user_id = ?";
		this.executeSql(executeSql, userId);
	}

	@Override
	public OrgUserRelation getUORelation(Long userId) {
		Criteria c = createCriteria(Restrictions.eq("userId", userId));
		Object obj = c.uniqueResult();
		if (null != obj) {
			return (OrgUserRelation) obj;
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<OrgUserRelation> getOURelations(Long orgId) {
		Criteria c = createCriteria(Restrictions.eq("orgId", orgId), Restrictions.isNotNull("userId"));
		return c.list();
	}

}
